import * as Http from 'http';
import * as Querystring from 'querystring';
import * as Url from 'url';

interface Response {
    statusCode?: number;
    statusMessage?: string;
    headers: Http.IncomingHttpHeaders;
    content: string;
}

interface PostOption {
    url: string;
    contentType?: string;
    params?: any;
    data?: any;
}

export async function get(url: string, params?: any) {
    return new Promise<Response>((resolve, reject) => {
        let real_url = url;
        if (params != undefined) {
            const qs = Querystring.stringify(params);
            if (qs) real_url += '?' + qs;
            console.log('real url: ', real_url);
        }
        Http.get(real_url, (res) => {
            res.setEncoding('utf8');
            const result: Response = {statusCode: res.statusCode,
                statusMessage: res.statusMessage,
                headers: res.headers, content: ''};
            res.on('data', (chunk) => result.content += chunk );
            res.on('end', () => { resolve(result); });
        }).on('error', (e) => {
            reject(e);
        });
    });
}

export async function post(opt: PostOption) {
    return new Promise<Response>((resolve, reject) => {
        let url_param = '';
        if (opt.params) url_param = Querystring.stringify(opt.params);
        let post_data = undefined;
        if (opt.data != undefined) {
            post_data = JSON.stringify(opt.data);
        }
        const url_opt = Url.parse(opt.url);
        const http_opt: Http.RequestOptions = {
            hostname: url_opt.hostname,
            port: url_opt.port,
            path: url_opt.path + (url_param && '?' + url_param),
            method: 'POST',
            headers: {
                'User-Agent': 'nodejs proxy server',
                'Accept': '*/*',
                'Content-Type': opt.contentType || "application/json;charset=utf8",
            }
        }
        if (post_data && http_opt.headers)
            http_opt.headers['Content-Length'] = Buffer.byteLength(post_data);

        let req = Http.request(http_opt, (res) => {
            res.setEncoding('utf8');
            const result: Response = {statusCode: res.statusCode,
                statusMessage: res.statusMessage,
                headers: res.headers, content: ''};
            res.on('data', (chunk) => result.content += chunk );
            res.on('end', () => { resolve(result); });
        }).on('error', (e) => {
            reject(e);
        });

        if (post_data) req.write(post_data);
        req.end();
    });
}